<template>
  <div>
    {{ message }}
  </div>
</template>
<script>
import { token } from '@/api/oauth2'

export default {
  name: 'OAuth2Authorized',
  props: {
    code: {
      type: String,
    },
    error: {
      type: String,
    },
    error_description: {
      type: String,
    },
  },
  data() {
    return {
      message: '正在获取code...',
    }
  },
  mounted() {
    if (!this.code) {
      this.message =
        '授权失败 ' +
        JSON.stringify({
          error: this.error,
          error_description: this.error_description,
        })
      return
    }

    let code_verifier = this.$store.getters.codeVerifier
    if (!code_verifier) {
      this.message = '本地 code_verifier 丢失'
      return
    }

    this.message = '获取code成功，正在申请令牌...'
    this.$store.commit('oauth2Client/SET_CODE', this.code)

    token({
      client_id: window.client.clientId,
      redirect_uri: window.client.redirectUri,
      code: this.code,
      code_verifier,
      grant_type: 'authorization_code',
      commonFormat: true,
    }).then((res) => {
      this.message = '令牌申请成功'
      this.$message.success(this.message)
      this.$store.commit('oauth2Client/SET_TOKEN', res.data.data)

      setTimeout(() => {
        this.$router.push('/index')
      }, 1000)
    })
  },
  methods: {},
}
</script>
